#include "widget.h"
#include "ui_widget.h"
#include "rfid.h"

#include <QByteArray>
#include <QDebug>
#include <QHostAddress>
#include <QBuffer>
#include <QFile>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    v4l2 = nullptr;
    m_rfidFd = -1;
    m_rfidThread = nullptr;
    m_rfidTimer = nullptr;

    // 初始化RFID读卡器在另一个线程中
    m_rfidThread = new QThread(this);

    // 初始化读卡定时器
    m_rfidTimer = new QTimer();
    m_rfidTimer->moveToThread(m_rfidThread);
    m_rfidTimer->setInterval(3000); // 3秒读卡一次

    // 连接信号槽
    connect(m_rfidThread, &QThread::started, [this]() {
        m_rfidFd = open_serial();
        if (m_rfidFd >= 0) {
            init_tty(m_rfidFd);
            timeout.tv_sec = 1;  // 设置超时时间
            timeout.tv_usec = 0;
            m_rfidTimer->start();
        }
    });


    connect(m_rfidTimer, &QTimer::timeout, [this]()
    {
        if (m_rfidFd < 0)
        {
            // 尝试重新打开串口
            m_rfidFd = open_serial();
            if (m_rfidFd >= 0)
            {
                init_tty(m_rfidFd);
                timeout.tv_sec = 1;
                timeout.tv_usec = 0;
            }
            return;
        }

        // 添加调试输出
        static int retryCount = 0;

        // 发送请求命令
        if (PiccRequest(m_rfidFd) == 0)
        {
            // 获取卡号
            if (PiccAnticoll(m_rfidFd) == 0 && cardid != 0)
            {
                qDebug() << "YES! ID:" << QString::number(cardid, 16);
                emit cardDetected(cardid);
                retryCount = 0;
            }
        }
        else
        {
            //qDebug() << "RFIDno:" <<retryCount;//调试
            if (++retryCount > 3)
            {
                // 多次失败后重新初始化串口
                ::close(m_rfidFd);
                m_rfidFd = open_serial();
                if (m_rfidFd >= 0) {
                    init_tty(m_rfidFd);
                    timeout.tv_sec = 1;
                    timeout.tv_usec = 0;
                }
                retryCount = 0;
            }
        }
    });

    connect(this, &Widget::cardDetected, this, &Widget::onCardDetected);

    // 启动RFID线程
    m_rfidThread->start();

    // 实例化摄像头定时器
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &Widget::onUpdateCameraUi);

    // 启动摄像头
    if (v4l2 == nullptr) {
        v4l2 = new V4l2Api("/dev/video7");
        v4l2->start();
        m_timer->start(80); // 80ms采集一次数据
    }

    // 初始化TCP服务器
    m_tcpServer = new QTcpServer(this);
    short port = 1234;
    m_tcpServer->listen(QHostAddress::Any, port);
    connect(m_tcpServer, &QTcpServer::newConnection, this, &Widget::onNewClientConnect);
}

Widget::~Widget()
{
    // 停止RFID线程
    if (m_rfidTimer) {
        m_rfidTimer->stop();
    }
    if (m_rfidThread) {
        m_rfidThread->quit();
        m_rfidThread->wait();
    }

    // 关闭串口
    if (m_rfidFd >= 0) {
        ::close(m_rfidFd);
    }

    delete m_rfidTimer;
    delete ui;

    // 停止摄像头
    if(v4l2)
    {
        v4l2->stop();
        v4l2->destory();
        delete v4l2;
    }
}

void Widget::onCardDetected(unsigned int cardId)
{
    // 如果有客户端连接，发送卡号
    if (tcpClient && tcpClient->state() == QAbstractSocket::ConnectedState)
    {
        QByteArray data;
        data.append("CARD:");
        data.append(QString::number(cardId).toUtf8());
        tcpClient->write(data);
        qDebug() << "Sent card ID:" << cardId;
    }
}

void  Widget::onNewClientConnect()
{
    qDebug()<<"connect succes";
    //在槽函数中获取新客户端的连接
    tcpClient = m_tcpServer->nextPendingConnection();
    //当有客户端发送数据的时候，tcpClient会触发readyRead信号，关联槽函数，接收数据
    connect(tcpClient,&QTcpSocket::readyRead,this,&Widget::onRecvDataSlot);

}

void Widget:: onRecvDataSlot()
{
   saveImg.save("2.bmp");
   //加载图图片
    QImage image("2.bmp");
   //将图片转换成字节数组
    QByteArray imgeData;
    QBuffer buffer(&imgeData);
    buffer.open(QIODevice::WriteOnly);
    image.save(&buffer,"BMP");
    //发送
    int ret =  tcpClient->write(imgeData);
    qDebug()<<ret;

//   saveImg.save("1.bmp");
//   system("scp 1.bmp gec@192.168.6.45:/mnt/hgfs/GZFX2302/11QT/build-car3-Desktop_Qt_5_14_2_MinGW_64_bit-Debug");
}

void Widget::onUpdateCameraUi()
{
    char buffer[640*480*3] = {0};
    char rgbdata[640*480*3] = {0};
    int size;
    //采集数据
    v4l2->get_frame(buffer,&size);

    //yuyv格式 转换成  rgb格式
    v4l2->yuv422torgb24((unsigned char*)buffer,(unsigned char*)rgbdata,640,480);

    //显示 ---rgbdata
    QImage img((unsigned char*)rgbdata,640,480,QImage::Format_RGB888);
    saveImg = img;
    QPixmap pic = QPixmap::fromImage(img);
    pic = pic.scaled(ui->label->size());
    ui->label->setPixmap(pic);

}


